package com.example.my_rabbitmq_high_demo.exchange.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: topic模式消费者
 * @Author: GaoJian
 * @Date: 2022/7/3 22:16
 */
public class ConsumerByTopic {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");

        //创建连接
        Connection connection = factory.newConnection();

        //创建channel
        Channel channel = connection.createChannel();

        //声明exchange
        String exchangeName = "test_topic_exchange";
        String exchangeType = "topic";
        //“#” : 匹配一个或多个词
        //“*” : 匹配一个词
        String routingKey = "tingxuelou.*";
        channel.exchangeDeclare(exchangeName, exchangeType);

        //声明队列
        String queueName = "test_topic_queue";
        //注意：交换机的持久化属性的值对队列持久化属性的值有一定限制
        channel.queueDeclare(queueName, false, false, false, null);

        //绑定队列
        channel.queueBind(queueName, exchangeName, routingKey);

        //创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println(new String(delivery.getBody()));
        }
    }
}
